<template>
    <u-popup :show="show" @close="close" mode="bottom" :round="10" :closeable="false">
        <view @touchmove.prevent.stop class="popup-common ">
            <view class="title ">{{ nowPaymenthds?.classiName }}</view>


            <scroll-view scroll-y="true" class="h-[70vh]  ">
                <view class="commission-bg sidebar-margin my-[var(--top-m)] rounded-[var(--rounded-big)] py-[30rpx]">

                    <view class="flex justify-around commission-content mb-[20rpx]">
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">订单金额(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(state.orderInfo.price.totalPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">已付金额(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(state.orderInfo.price.paidPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">待支付金额(元)</text>
                            <text
                                class=" price-font  text-[var(--price-text-color)]  text-[38rpx] font-500 mt-[16rpx]">{{
                                    fen2yuan(state.orderInfo.price.payPrice
                                    ) }}</text>
                        </view>
                    </view>
                    <up-line dashed></up-line>

                    <view class="flex justify-around commission-content mt-[20rpx]">
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">欠款金额(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(state.orderInfo.price.arrearsPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">优惠金额(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(state.orderInfo.price.givePrice
                                ) }}</text>
                        </view>

                    </view>
                </view>
                <view class="card-template mt-[30rpx]">
                    <view class="font-500 text-[34rpx] text-[#333] leading-[42rpx]">{{ inputLabel }}
                    </view>
                    <view
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <text class="pt-[4rpx] text-[40rpx] text-[#333] iconfont iconrenminbiV6xx price-font "></text>
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 price-font text-[44rpx] bg-[#fff]"
                            v-model="nowPayment.usePayBalance" maxlength="7" :placeholder="`请输入${inputLabel}`"
                            placeholder-class="apply-price" :adjust-position="false" />
                        <text @click="onHandleCancel" v-if="nowPayment.usePayBalance"
                            class="nc-iconfont nc-icon-cuohaoV6xx1 !text-[44rpx] text-[var(--text-color-light9)]"></text>
                    </view>
                    <view class="pt-[16rpx] flex items-center justify-between px-[4rpx]">
                        <view class="text-[34rpx] text-[var(--text-color-light6)] price-font leading-[36rpx]">
                            <text v-if="nowPaymenthds.classify == 'wallet'">可用余额:￥{{
                                fen2yuan(nowPayment?.usableBalance || 0) }}</text>
                        </view>
                        <view class="text-[34rpx] text-primary leading-[36rpx]" v-if="nowPayment.usePayBalance != ''"
                            @click="onHandleCancel()">取消使用
                        </view>
                        <view class="text-[34rpx] text-primary leading-[36rpx]" v-if="!nowPayment.usePayBalance"
                            @click="handleAllPay()">全额支付
                        </view>
                    </view>
                </view>

            </scroll-view>
            <!-- <u-keyboard mode="number" @change="valChange" @backspace="backspace" :overlay="false" :showTips="false"
                :tooltip="false" safeAreaInsetBottom :show="show" class="keyboard-common">
            </u-keyboard> -->
            <view class="btn-wrap">
                <button class="primary-btn-bg btn" :loading="submitLoading" @click="confirm">确认</button>
            </view>
        </view>
    </u-popup>
    <!-- 合利宝付款码支付 -->
    <view @touchmove.prevent.stop>
        <u-popup class="popup-type" :show="barCode.visible" @close="barCode.visible = false" zIndex="10082">
            <view class="min-h-[360rpx] popup-common" @touchmove.prevent.stop>
                <view class="title">合利宝付款码支付</view>
                <scroll-view class="h-[520rpx] mt-[10rpx]" scroll-y="true">
                    <view class="bg-white flex items-center leading-[30rpx] px-[var(--pad-sidebar-m)]">
                        <view class="text-[40rpx] text-[#303133]">支付条形码</view>
                        <view class="flex-1 text-[#303133] flex  justify-end items-center">
                            <input type="text" v-model="barCode.value" class="text-right text-[#333] text-[40rpx]"
                                maxlength="50" placeholder="请输入支付条形码"
                                placeholder-class="text-[var(--text-color-light9)] text-[40rpx]">
                            <!--  #ifndef  H5 -->
                            <!-- <u-icon name="scan" color="#999" size="40" @click="handelScan"></u-icon> -->
                            <!-- #endif -->

                        </view>
                    </view>
                    <view class="bg-white flex flex-col items-center leading-[30rpx] px-[var(--pad-sidebar-m)]">
                        <view class="flex-1 text-[#303133] flex  justify-end items-center">

                            <!--  #ifndef  H5 -->
                            <u-icon name="scan" color="#999" size="200" @click="handelScan"></u-icon>
                            <!-- #endif -->

                        </view>
                        <view class="text-[40rpx] text-[#303133]">点击上方扫描支付条码</view>

                    </view>
                </scroll-view>
                <view class="btn-wrap">
                    <button :loading="submitLoading" class="primary-btn-bg btn" hover-class="none"
                        @click="submit0(nowPayment.assetsId)">
                        确认支付
                    </button>
                </view>
            </view>
        </u-popup>
    </view>
    <!-- 合利宝扫码支付 -->
    <view @touchmove.prevent.stop>
        <u-popup class="popup-type" :show="qrCode.visible" @close="clearQueryInterval()" zIndex="10082">
            <view class="min-h-[360rpx] popup-common" @touchmove.prevent.stop>
                <view class="title">合利宝扫描支付</view>
                <scroll-view class="h-[520rpx] mt-[10rpx]" scroll-y="true">
                    <view class="bg-white flex items-center flex-col leading-[30rpx] px-[var(--pad-sidebar-m)]">
                        <view class="text-[40rpx] text-[#303133] mb-[20rpx]">请使用微信“扫一扫”扫码支付</view>
                        <view
                            class=" rounded-[30rpx] box-border relative flex flex-col items-center justify-center  w-[400rpx] h-[400rpx]">

                            <l-painter v-if="qrCode.visible">
                                <l-painter-qrcode :text="qrCode.url" css="width: 360rpx; height: 360rpx" />
                            </l-painter>
                        </view>
                    </view>
                </scroll-view>
                <view class="btn-wrap">
                    <button :loading="submitLoading" class="primary-btn-bg btn" hover-class="none"
                        @click="clearQueryInterval()">
                        取消支付
                    </button>
                </view>
            </view>
        </u-popup>
    </view>

</template>
<script setup lang="ts">
import { ref, watch, computed, reactive } from 'vue'
import { fen2yuan, yuan2fen } from '@/utils/formatting';
import { beforeSubmit, secondSubmit, getSinglePayOrder } from '@/app/api/pay'
import { deepClone } from '@/utils/common';

const PayDisplayModeEnum = {
    URL: {
        mode: 'url'
    },
    IFRAME: {
        mode: 'iframe'
    },
    FORM: {
        mode: 'form'
    },
    QR_CODE: {
        mode: 'qr_code'
    },
    APP: {
        mode: 'app'
    },
    BAR_CODE: {
        mode: 'bar_code'
    }
}
const qrCode = ref({
    // 展示形式：二维码
    url: '',
    title: '',
    visible: false
})
const barCode = ref({
    // 展示形式：条形码
    channelCode: '',
    value: '',
    title: '',
    visible: false
})
const props = defineProps({
    orderInfo: {
        type: Object,
        default: () => {
            return {

            }
        }
    }, //订单信息
    paymentMap: {
        type: Array,
        default: () => {
            return []
        }
    },
    sceneType: {
        type: String,
        default: 'first'
    }
})

const nowPaymenthds = ref() //当前使用的资产
const state = reactive({
    orderInfo: computed(() => {
        return props.orderInfo
    }), // 支付单信息
    sceneType: computed(() => {
        return props.sceneType
    }),
    payMethods: computed(() => {
        return props.paymentMap.find((ele: any) => {
            return ele.classify == nowPaymenthds.value.classify
        })
    }) as any, // 可选的支付方式
    payment: '', // 选中的支付方式
    payOrderList: [] as any, //当前支付方式的支付流水号
    activeName: '', //当前选中的支付方式
})
const inputLabel = computed(() => {
    let label = '收款金额'
    console.log(nowPayment.value)
    if (nowPaymenthds.value.classify == 'ppc' || nowPaymenthds.value.classify == 'wallet') {
        label = '使用金额'
    } else if (nowPaymenthds.value.classify == 'change') {
        label = '优惠后金额'
    } else if (nowPaymenthds.value.classify == 'cart') {
        label = '累计抵扣'
    } else if (nowPaymenthds.value.classify == 'points') {
        label = '使用积分'
    }
    return label
})
const handleAllPay = () => {
    console.log(nowPaymenthds.value)

    console.log(nowPayment.value)

    if (nowPaymenthds.value.group == 'inside') {
        // 如果可用余额大于待支付金额 支付金额就是待支付金额
        if (state.orderInfo.price.payPrice < nowPayment.value!.usableBalance) {
            nowPayment.value.usePayBalance = fen2yuan(state.orderInfo.price.payPrice)
        } else {
            nowPayment.value.usePayBalance = fen2yuan(nowPayment.value!.usableBalance)
        }
        return
    }
    nowPayment.value.usePayBalance = fen2yuan(state.orderInfo.price.payPrice)
    console.log(nowPayment.value.usePayBalance)

    // onConfirm()
}
const nowPayment = ref<any>({})
const nowPaymentIndex = ref<any>() //当前支付方式的下标
// 监听支付方式的变化
watch(
    () => props.paymentMap,
    () => {
        if (nowPaymentIndex.value == undefined) {
            return
        }

        nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
        if (nowPayment.value.payStatus) {
            nowPayment.value.usePayBalance = fen2yuan(nowPayment.value.paybalance)
        } else {
            nowPayment.value.usePayBalance = ''
        }
    }
)

const show = ref(false)
const emits = defineEmits(['confirm', 'success'])
const valChange = (val: any) => {

    nowPayment.value.usePayBalance += val;

};

const backspace = () => {
    // 删除value的最后一个字符
    if (nowPayment.value.usePayBalance.length) {
        nowPayment.value.usePayBalance = nowPayment.value.usePayBalance.substr(0, nowPayment.value.usePayBalance.length - 1);
    }
};
// 清空提现金额
const clearMoney = () => {
    nowPayment.value.usePayBalance = '';
}





const close = () => {
    show.value = false


}
const selectPayMent = (index: any) => {
    nowPaymentIndex.value = index
    let item = state.payMethods.items[nowPaymentIndex.value]
    nowPayment.value = item
    if (item.payStatus) {
        nowPayment.value.usePayBalance = fen2yuan(nowPayment.value.paybalance)
    } else {
        nowPayment.value.usePayBalance = ''
    }
}
const setNowPayment = () => {
    let selectPayMentIndexs = [] as any
    state.payMethods.items.forEach((element: any, index: any) => {
        if (element.payStatus) {
            selectPayMentIndexs.push(index)
        }
    })

    if (selectPayMentIndexs.length == 0) {
        nowPayment.value = {}
        selectPayMent(0)
    } else {
        nowPaymentIndex.value = selectPayMentIndexs[0]
        nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
        state.activeName = nowPayment.value.assetsTitle
        nowPayment.value.usePayBalance = fen2yuan(nowPayment.value.paybalance)
    }
} //设置当前选中的支付方式
const open = (payMethods: any) => {
    show.value = true
    nowPaymenthds.value = payMethods
    setNowPayment()

}


const operationOrtherLogic = ref(['ppc', 'coupon', 'cart']) //用户资产
/** 提交支付前（条形码支付） */
const displayBarCode = (channelCode: any) => {

    barCode.value = {
        channelCode: channelCode,
        value: '',
        title: '条码支付',
        visible: true
    }
}
/** 提交支付后（扫码支付） */
const displayQrCode = (channelCode: any, data: any) => {
    let title = '请使用手机浏览器“扫一扫”'
    if (channelCode.indexOf('wx_') === 0) {
        title = '请使用微信“扫一扫”扫码支付'
    }
    qrCode.value = {
        title: title,
        url: data.displayContent,
        visible: true
    }
    submitLoading.value = false
}
const submit = (channelCode: any) => {
    // 条形码支付，需要特殊处理
    if (nowPayment.value.displayMode === PayDisplayModeEnum.BAR_CODE.mode) {
        displayBarCode(channelCode)
        return
    }

    //   // 微信公众号、小程序支付，无法在 PC 网页中进行
    //   if (channelCode === PayChannelEnum.WX_PUB.code) {
    //     message.error('微信公众号支付：不支持 PC 网站')
    //     return
    //   }
    //   if (channelCode === PayChannelEnum.WX_LITE.code) {
    //     message.error('微信小程序：不支持 PC 网站')
    //     return
    //   }

    // 默认的提交处理
    submit0(channelCode)
}
const submitLoading = ref(false)
const submit0 = async (channelCode) => {
    submitLoading.value = true
    let no = uni.getStorageSync('orderCreateData') && uni.getStorageSync('orderCreateData').no
    let userId = uni.getStorageSync('wapShopMember') && uni.getStorageSync('wapShopMember').id;
    try {
        const formData = {
            no: no,
            userId: userId,
            pay: {
                classify: nowPaymenthds.value.classify,
                // payStatus: nowPayment.value.payStatus,
                assetsId: nowPayment.value.assetsId,
                paybalance: yuan2fen(nowPayment.value.usePayBalance)
            },
            ...buildSubmitParam()
        }
        let payData = {} as any
        console.log(state.sceneType)

        if (state.sceneType == 'first') {
            const { data } = await beforeSubmit(formData)
            payData = data
        }
        if (state.sceneType == 'second') {
            let paramsData = deepClone(formData) as any
            paramsData.payOrderId = props.orderInfo.payOrderId
            const { data } = await secondSubmit(paramsData)
            payData = data

        }

        submitLoading.value = false


        console.log(payData)

        // // 直接返回已支付的情况，例如说扫码支付
        if (payData.status === 10) {
            clearQueryInterval()
            // uni.showToast({
            //     title: '支付成功',
            //     icon: 'none'
            // })
            close()

            // getAppChannelPayOrderList()
            return
        }
        if (payData.displayMode === PayDisplayModeEnum.QR_CODE.mode) {
            displayQrCode(channelCode, payData)
        }


        nowPayment.value.payOrderId = payData.id //当前支付的支付单号
        // // 打开轮询任务
        createQueryInterval()
    } finally {
        submitLoading.value = false
    }
}
/** 构建提交支付的额外参数 */
const buildSubmitParam = () => {
    if (nowPayment.value.displayMode === PayDisplayModeEnum.BAR_CODE.mode) {
        return {
            channelExtras: {
                authCode: barCode.value.value
            }
        }
    }

    return {}
}
/**
 * 扫码支付
 */
const handelScan = () => {
    // 调起条码扫描
    uni.scanCode({
        scanType: ['barCode'],
        onlyFromCamera: true,
        success: function (res) {
            console.log('条码类型：' + res.scanType);
            console.log('条码内容：' + res.result);
            barCode.value.value = res.result
            submit0(nowPayment.value.assetsId)
        }
    });
}
/** 轮询查询任务 */
const interval = ref<any>(undefined) // 定时任务，轮询是否完成支付
const countDownTime = ref(Date.now() + 1000 * 60)
const createQueryInterval = () => {
    if (barCode.value.visible) {
        uni.showLoading()

    }
    if (interval.value) {
        return
    }
    interval.value = setInterval(async () => {
        let paramsData = {
            payOrderId: nowPayment.value.payOrderId,
            channelCode: nowPayment.value.assetsId,
            sync: true
        }
        const { data } = await getSinglePayOrder(paramsData)

        // 已支付
        if (data.status === 10) {
            clearQueryInterval()
            uni.showToast({
                title: '支付成功！',
                icon: 'none'
            })
            // await getAppChannelPayOrderList()
        }
        // 已取消
        if (data.status === 20) {
            clearQueryInterval()
            uni.showToast({
                title: '支付已关闭！',
                icon: 'none'
            })
            // await getAppChannelPayOrderList()
            // goReturnUrl('close')
        }
    }, 1000 * 2)
}
/** 清空查询任务 */
const clearQueryInterval = (type?: string) => {
    uni.hideLoading()

    countDownTime.value = Date.now() + 1000 * 60

    // // 清空各种弹窗
    qrCode.value = {
        title: '',
        url: '',
        visible: false
    }
    barCode.value = {
        channelCode: '',
        value: '',
        title: '条码支付',
        visible: false
    }
    // // 清空任务
    clearInterval(interval.value)
    interval.value = undefined

    emits('success')
    close()


}


const confirm = () => {
    console.log(nowPaymenthds.value)

    console.log(nowPayment.value)
    if (!nowPayment.value.usePayBalance) {
        uni.showToast({
            title: '支付金额不能为空',
            icon: 'none'
        })
        return
    }

    if (Number(nowPayment.value.usePayBalance) < 0) {
        uni.showToast({
            title: '支付金额必须大于0',
            icon: 'none'
        })
        return
    }
    if (operationOrtherLogic.value.includes(nowPayment.value.classify)) {
        return
    } else if (nowPaymenthds.value.classify == 'wallet') {
        let item = nowPayment.value
        item.payStatus = true
        item.paybalance = yuan2fen(nowPayment.value.usePayBalance)
        emits('confirm', item, nowPaymenthds.value.classify)
        close()
        return
    } else {
        // let item = nowPayment.value.items[0]
        // item.payStatus = true
        // emit('handleUsePaymentPay', item, nowPayment.value.classify)

        // submit(nowPayment.value.items[0].assetsId)
        submit(nowPayment.value.assetsId)
    }





}
const onHandleCancel = () => {
    clearMoney()
    let item = state.payMethods.items[nowPaymentIndex.value]
    item.payStatus = false

    emits('confirm', item, nowPaymenthds.value.classify)
}

defineExpose({
    open,

})
</script>
<script lang="ts">
export default {
    options: {
        styleIsolation: 'shared'
    }
}  
</script>
<style lang="scss" scoped>
:deep(.apply-price) {
    color: var(--text-color-light9);
    font-size: 34rpx;
    font-weight: normal;
    line-height: 76rpx;
}

.popup-common .title {
    font-weight: 500;
    text-align: center;
    font-size: 1.125rem;
    padding-top: 1.125rem;
    line-height: 1;
    padding-bottom: 0;
}

.commission-bg {
    background: #f6f6f6;
}

.commission-content>view {
    position: relative;
    width: 6.5625rem
}

.commission-content>view:after {
    content: "";
    position: absolute;
    width: .0625rem;
    height: 1.875rem;
    background-color: var(--temp-bg);
    top: 50%;
    right: 0;
    transform: translateY(-50%)
}

.commission-content>view:last-of-type:after {
    width: 0;
    height: 0
}
</style>